import { Button, Form, Input, Modal, Select, message } from 'antd';
import React, { useEffect, useState } from 'react';
import TextEditor from '@/components/TextEditor';
import { updateArticle } from '@/services/articleService';
import { getAdminDictionaryAll } from '@/services/adminDictionaryService';
import type { SelectProps } from 'antd';
import DynamicTag from '@/components/DynamicTag';
import UploadImg from '@/components/UploadComponent';

interface Props {
  modalVisible: boolean;
  onSubmit: () => void;
  onCancel: () => void;
  article: ArticleType.ArticleResponse
};

const UpdateModal: React.FC<Props> = (props) => {
  const { modalVisible, onSubmit, onCancel, article } = props;
  const [form] = Form.useForm();
  const [imgUrl, setImgUrl] = useState<string>(article.ImgUrl);
  const [tags, setTags] = useState<string[]>();
  const [content, setContent] = useState<string>('');
  const [typeList, setTypeList] = useState<SelectProps['options']>([]);
  form.setFieldValue("Title", article.Title);
  form.setFieldValue("TypeId", article.TypeId.split(',').map(r => parseInt(r)));
  form.setFieldValue("Summary", article.Summary);

  const saveArticle = () => {
    form.validateFields({ validateOnly: false })
      .then(() => {
        updateArticle({ ...article, ...form.getFieldsValue(), ImgUrl: imgUrl, Content: content, TypeId: Array(form.getFieldValue("TypeId")).join(','), UpdateTime: new Date(), Tag: tags?.join(',') }).then(result => {
          const { StatusCode } = result;
          if (StatusCode === 0) {
            message.success("保存成功！");
            onSubmit?.();
          }
        })
      }, () => {
      })
  }

  const loadDictionaryList = async () => {
    getAdminDictionaryAll({ "@fields": "Id,Value" }).then(result => {
      const { Items } = result;
      setTypeList(Items.map((r: any) => {
        return {
          label: r.Value,
          value: r.Id,
        }
      }));
    })
  }

  useEffect(() => {
    loadDictionaryList();
  }, [])

  return (
    <Modal
      width={700}
      destroyOnClose
      title="新建"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={[
        <Button key="submit" onClick={saveArticle} type="primary">
          保存
        </Button>,
        <Button key="back" onClick={onCancel} >
          取消
        </Button>,
      ]}
    >
      <Form
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        style={{ maxWidth: 600 }}
        form={form}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <Form.Item<ArticleType.ArticleRequest>
          label="标题"
          name="Title"
          rules={[{ required: true, message: '请填入标题!' }]}
        >
          <Input name='title' type='text' />
        </Form.Item>
        <Form.Item<ArticleType.ArticleRequest>
          label="封面"
          name="Title"
          rules={[{ required: true, message: '请上传封面!' }]}
        >
          <UploadImg callBack={setImgUrl} />
        </Form.Item>
        <Form.Item<ArticleType.ArticleRequest>
          label="分类"
          name="TypeId"
          rules={[{ required: true, message: '请选择分类!' }]}
        >
          <Select
            placeholder="请选择分类"
            allowClear
            mode="multiple"
            defaultValue={article.TypeId.split(',').map(r => parseInt(r))}
            options={typeList}
          />
        </Form.Item>
        <Form.Item<ArticleType.ArticleRequest>
          label="自定义标签"
          name="Tag"
        >
          <DynamicTag callBack={setTags} initialTags={article.Tag.split(',')} />
        </Form.Item>
        <Form.Item<ArticleType.ArticleRequest>
          label="简介"
          name="Summary"
          rules={[{ required: true, message: '请填入简介!' }]}
        >
          <Input name='summary' type='text' />
        </Form.Item>
        <Form.Item<ArticleType.ArticleRequest>
          label="内容"
          name="Content"
        >
          <TextEditor initialValue={article.Content} valueChange={setContent} />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default UpdateModal;
